import React, { useRef, useState, useEffect } from 'react';
import './style.scss';

const CustomVideoPlayer = ({
    src,
    poster,
    onVideoClick,
    controls,
    style,
    id, // 视频ID
    num, // 视频序号
    onPlay, // 播放回调，用于设置全局状态
    isPlaying, // 根据全局状态判断是否播放
    onPauseOnClick, // 新增：点击非视频区域时暂停的回调
}) => {
    const videoRef = useRef(null);
    const containerRef = useRef(null);
    const progressRef = useRef(null);
    const [isLoaded, setIsLoaded] = useState(false);
    const [isVisible, setIsVisible] = useState(false);
    const [duration, setDuration] = useState(0);
    const [currentTime, setCurrentTime] = useState(0);
    const [isDragging, setIsDragging] = useState(false);

    // useEffect(() => {
    //     const observer = new IntersectionObserver(
    //         ([entry]) => {
    //             console.log(entry.isIntersecting, 'entry.isIntersecting');
    //             if (entry.isIntersecting) {
    //                 setIsVisible(true);
    //                 observer.disconnect();
    //             }
    //         },
    //         { root: null, threshold: 0.1 }
    //     );

    //     if (containerRef.current) {
    //         observer.observe(containerRef.current);
    //     }

    //     return () => observer.disconnect();
    // }, []);

    useEffect(() => {
        const container = containerRef.current;
        if (!container) return;

        const checkVisibility = () => {
            const rect = container.getBoundingClientRect();
            const isInViewport =
                rect.top < window.innerHeight &&
                rect.bottom > 0 &&
                rect.left < window.innerWidth &&
                rect.right > 0;

            // 添加额外的检查，确保元素在合理的范围内
            const isReasonablyPositioned = rect.top < window.innerHeight * 3;

            if (isInViewport && isReasonablyPositioned) {
                setIsVisible(true);
                observer.disconnect();
            }
        };

        const observer = new IntersectionObserver(
            ([entry]) => {
                if (entry?.isIntersecting) {
                    setIsVisible(true);
                    observer.disconnect();
                }
            },
            { root: null, threshold: 0.01 }
        );

        observer.observe(container);

        // 延迟检查以确保布局稳定
        const timer = setTimeout(checkVisibility, 100);

        return () => {
            clearTimeout(timer);
            observer.disconnect();
        };
    }, []);

    // 监听外部播放状态变化
    useEffect(() => {
        if (isPlaying !== undefined) {
            if (isPlaying) {
                playVideo();
            } else {
                pauseVideo();
            }
        }
    }, [isPlaying]);

    // 加载元数据
    const handleLoadedMetadata = (e) => {
        setDuration(e.target.duration);
        setIsLoaded(true);
    };

    const handleTimeUpdate = (e) => {
        if (!isDragging) {
            setCurrentTime(e.target.currentTime);
        }
    };

    const playVideo = () => {
        if (!isLoaded || !videoRef.current) return;

        const video = videoRef.current;
        const playPromise = video.play();
        if (playPromise !== undefined) {
            playPromise.catch((error) => {
                console.error('自动播放被阻止:', error);
            });
        }
    };

    const pauseVideo = () => {
        if (!videoRef.current) return;
        videoRef.current.pause();
    };

    const togglePlay = () => {
        if (!isLoaded) return;

        if (isPlaying) {
            // 当前正在播放，点击停止
            pauseVideo();
            onPlay?.(id, num, false); // 通知父组件停止播放
        } else {
            // 当前未播放，点击开始播放
            playVideo();
            onPlay?.(id, num, true); // 通知父组件开始播放
        }
    };

    // 进度条点击
    const handleProgressClick = (e) => {
        if (!progressRef.current || !videoRef.current) return;

        const rect = progressRef.current.getBoundingClientRect();
        const clickX = e.clientX - rect.left;
        const percentage = clickX / rect.width;
        const newTime = percentage * duration;

        videoRef.current.currentTime = newTime;
        setCurrentTime(newTime);
    };

    // 进度条拖拽
    const handleProgressMouseDown = (e) => {
        setIsDragging(true);
        handleProgressClick(e);
    };

    const handleProgressMouseMove = (e) => {
        if (isDragging) {
            handleProgressClick(e);
        }
    };

    const handleProgressMouseUp = () => {
        setIsDragging(false);
    };

    // 全局鼠标事件监听
    useEffect(() => {
        if (isDragging) {
            const handleGlobalMouseMove = (e) => {
                handleProgressMouseMove(e);
            };

            const handleGlobalMouseUp = () => {
                setIsDragging(false);
            };

            document.addEventListener('mousemove', handleGlobalMouseMove);
            document.addEventListener('mouseup', handleGlobalMouseUp);

            return () => {
                document.removeEventListener(
                    'mousemove',
                    handleGlobalMouseMove
                );
                document.removeEventListener('mouseup', handleGlobalMouseUp);
            };
        }
    }, [isDragging, duration]);

    // 点击视频区域（非 controls）触发自定义行为
    const handleContainerClick = (e) => {
        if (e.target.closest('.custom-controls')) {
            return; // 不触发 onVideoClick
        }

        // 如果当前视频正在播放，先暂停
        if (isPlaying) {
            pauseVideo();
            onPlay?.(id, num, false); // 通知父组件停止播放
        }

        // 触发弹窗
        onVideoClick?.(e);

        // 触发暂停回调（用于其他逻辑）
        onPauseOnClick?.(id, num);
    };

    return (
        <div
            ref={containerRef}
            onClick={handleContainerClick}
            className="relative-container custom-video-player"
            style={{
                ...style,
            }}
        >
            <div
                className="poster-div"
                style={{
                    background: `url(${poster}) center/contain no-repeat`,
                    zIndex: isLoaded ? 1 : 3, // 加载后降级
                }}
            />

            {isVisible && (
                <video
                    ref={videoRef}
                    src={src}
                    preload="metadata"
                    onLoadedMetadata={handleLoadedMetadata}
                    onTimeUpdate={handleTimeUpdate}
                    onPlay={() => {
                        // 视频开始播放时，确保状态同步
                        if (!isPlaying) {
                            onPlay?.(id, num, true);
                        }
                    }}
                    onPause={() => {
                        // 视频暂停时，确保状态同步
                        if (isPlaying) {
                            onPlay?.(id, num, false);
                        }
                    }}
                    onEnded={() => {
                        // 视频结束时，自动停止
                        onPlay?.(id, num, false);
                    }}
                    style={{
                        width: '100%',
                        height: '100%',
                        objectFit: 'contain',
                        zIndex: 2,
                        position: 'relative',
                    }}
                    playsInline
                    muted
                />
            )}

            <div className="custom-controls">
                <button
                    className="playorpause-btn"
                    style={{
                        cursor: 'pointer',
                    }}
                    onClick={(e) => {
                        e.stopPropagation(); // 阻止冒泡到 container
                        togglePlay();
                    }}
                >
                    {isPlaying ? (
                        <img
                            src="https://img.alicdn.com/imgextra/i3/O1CN01kQzgqk1t6jGCLGhv7_!!6000000005853-55-tps-7-10.svg"
                            alt=""
                        />
                    ) : (
                        <img src="https://img.alicdn.com/imgextra/i2/O1CN01QTtdhg1dyk7M2C4e4_!!6000000003805-2-tps-13-14.png" />
                    )}
                </button>
                <span className="time-text">
                    {formatTime(currentTime)} / {formatTime(duration)}
                </span>

                <div
                    ref={progressRef}
                    className="video-progress"
                    onMouseDown={handleProgressMouseDown}
                    onMouseMove={handleProgressMouseMove}
                    onMouseUp={handleProgressMouseUp}
                    style={{ cursor: 'pointer' }}
                >
                    <div
                        style={{
                            width: `${(currentTime / duration) * 100 || 0}%`,
                            height: '100%',
                            background: ' #fff',
                            borderRadius: '2px',
                            transition: isDragging ? 'none' : 'width 0.1s ease',
                        }}
                    />
                </div>
            </div>

            {/* 加载中提示 */}
            {!isLoaded && isVisible && (
                <div
                    style={{
                        position: 'absolute',
                        top: '50%',
                        left: '50%',
                        transform: 'translate(-50%, -50%)',
                        color: 'white',
                        zIndex: 5,
                        background: 'rgba(0,0,0,0.7)',
                        padding: '10px 15px',
                        borderRadius: '6px',
                    }}
                >
                    加载中...
                </div>
            )}
        </div>
    );
};

// 工具函数
function formatTime(seconds) {
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins}:${secs.toString().padStart(2, '0')}`;
}

export default CustomVideoPlayer;
